<?php
// In addition to being an example child theme for the CalPress theme, North Gate theme provides the base functionality 
// for several UC Berkeley Graduate School of Journalism publication sites. Paths in functions in this file may seem
// a bit complicated. The Berkeley sites are CalPress child themes that also include this file, and import the North Gate CSS as a 
// higher-level start above CalPress' basic CSS, hence the use of the NORTHGATEINCLUDEPATH constant. For North Gate,
// this constant points right back to this location. For other themes, it points to the includes file in those themes. 
// And, those other themes can fall back on to includes in this directory if they don't exist in their directory. This
// is a crude way of faking three levels of inheritance, when WP only supports two in its Parent/Child theme framework construct.
// I sometimes refer to North Gate-based Berkeley sites as "grandchild" sites of CalPress. 

// Determine if included files should come from North Gate Theme, or 
// the location of a calling script. 
$northgatethemepath = trim(str_replace("/library/".basename(__FILE__), "", realpath(__FILE__)));
$currentthemepath = trim(realpath(STYLESHEETPATH));
$is_northgate = false;
if ($currentthemepath === $northgatethemepath) {
    $is_northgate = true;
    define('NORTHGATEINCLUDEPATH', $northgatethemepath."/includes");
    
} else {
    define('NORTHGATEINCLUDEPATH', $currentthemepath."/includes");
}

// function to include files from either North Gate or grandchild theme
function northgate_include_file($localfile){
    global $is_northgate;
    global $northgatethemepath;
    global $currentthemepath;
    
    if ($is_northgate) {
        include($northgatethemepath."/".$localfile);
    } else {
        // check to see if grandchild theme has desired file. If not, use North Gate's
        if ( file_exists($currentthemepath."/".$localfile) ) {
            include($currentthemepath."/".$localfile);
        } else {
            include($northgatethemepath."/".$localfile);
        }
   }
}

// function to see if a file to include exist in either NG or grand child theme. 
// useful in conjuction with northgate_include_file
function northgate_include_file_exists($localfile){
    global $northgatethemepath;
    global $currentthemepath;
    
    // check to see if grandchild theme has desired file. If not, check North Gate's
    if ( file_exists($currentthemepath."/".$localfile) ) {
        return true;
    } elseif( file_exists($northgatethemepath."/".$localfile) ) {
        return true;
    } else {
        return false;
    }
}

// Load template functionality needed for all North Gate sites

// Register widgetable areas in footer
northgate_instantiate_widgets();
// Instantiate North Gate 3-col widget-able footer
northgate_instantiate_footer();
// Header init functions
northgate_template_init();
// Cram standard stuff into <head>
northgate_template_header();
northgate_random_featured_comment();
// Tab builder on author pages
northgate_template_author_tabs();


// make widget holders
function northgate_instantiate_widgets(){
    if ( function_exists('register_sidebar') ) { 
      
        register_sidebar(array(
        'name' => 'Additional Sidebar Items',
        'id' => 'featured-story',
        'before_widget' => '<li>',
        'after_widget' => "</li>",
        'before_title' => "<h3 style=\"display:none;\">",
        'after_title' => "</h3>"
        ));
        
        register_sidebar(array(
        'name' => 'Text Advertisements',
        'id' => 'advertisement',
        'before_widget' => '<li>',
        'after_widget' => "</li>",
        'before_title' => "",
        'after_title' => ""
        ));
        
        register_sidebar(array(
         'name' => 'Footer Column 1',
         'id' => 'footer-col1',
         'before_widget' => '<li>',
         'after_widget' => "</li>",
         'before_title' => "<h3>",
         'after_title' => "</h3>"
         ));

         register_sidebar(array(
          'name' => 'Footer Column 2',
          'id' => 'footer-col2',
          'before_widget' => '<li>',
          'after_widget' => "</li>",
          'before_title' => "<h3>",
          'after_title' => "</h3>"
          ));

        register_sidebar(array(
        'name' => 'Footer Column 3',
        'id' => 'footer-col3',
        'before_widget' => '<li>',
        'after_widget' => "</li>",
        'before_title' => "<h3>",
        'after_title' => "</h3>"
        ));
        

    }
}

// Functions to take place before WP starts any other page bulding
function northgate_template_init(){
    add_action('init', 'northgate_init');
    function northgate_init() {
        if( !is_admin()){
            wp_deregister_script('jquery-ui-core');
       	    wp_enqueue_script('jquery-ui-core', ("http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.4/jquery-ui.min.js"), array('jquery'), '1.8.4');
       	    // North Gate JS
       	    wp_enqueue_script('northgate-core', (BASEURL  .'/wp-content/themes/northgate/js/northgate.js'), array('jquery'));
    	}
    }
}

// Insert North Gate footer into CalPress' footer template
function northgate_instantiate_footer(){
    add_action('calpress_hook_footer', 'northgate_template_footer');
    function northgate_template_footer() {
       northgate_include_file('includes/footer-include.php');
    }
}

// Insert ad into header
function northgate_template_headerad(){
    add_action('calpress_hook_header_posttitle', 'headerad');
    function headerad() {
       northgate_include_file('includes/ad-header.php');
    }
}

// Insert ad below article
function northgate_template_articlebottomad(){
    add_action('calpress_hook_postcontent_below', 'articlebottomad');
    function articlebottomad() {
       northgate_include_file('includes/ad-articlebottom.php');
    }
}

// Insert ad into header
function northgate_template_prewrapperad(){
    add_action('calpress_hook_prewrapper', 'prewrapperad');
    function prewrapperad() {
       northgate_include_file('includes/ad-prewrapper.php');
    }
}

// Insert North Gate features below CalPress' front page loop
function northgate_template_front_features(){
    add_action('calpress_hook_frontfeatures_below', 'front_features');
    function front_features() {
       northgate_include_file('includes/home-features.php');
    }
}

// Insert txt into <head>
function northgate_template_header(){
    
    // North Gates IE CSS
    add_action('wp_head', 'ng_ie_css');
    function ng_ie_css(){
        echo '
            <!--[if IE ]>
                <link href="'. BASEURL  .'/wp-content/themes/northgate/css/ie.css" rel="stylesheet" type="text/css"/>
            <![endif]-->
        ';
    }
    
    // North Gate's CSS for jQuery UI
    add_action('wp_head', 'jquery_ui_css');
    function jquery_ui_css(){
        echo '<link href="'. BASEURL  .'/wp-content/themes/northgate/css/jquery-ui-northgate.css" rel="stylesheet" type="text/css"/>';
    }
    
}

// On author pages, add UL for necessary tab elements
function northgate_template_author_tabs(){
    
    // Add UL to turn into tabs above stories and comments on author page
    add_action('calpress_hook_authorpage_precontributedcontent', 'author_tabs');
    function author_tabs() {
    
        echo '<ul>';
            echo '<li><a href="#author-comments">Comments</a></li>';
            echo '<li><a href="#author-stories">Stories</a></li>';
            echo '<li><a href="#author-twitter">Twitter</a></li>';
        echo '</ul>';
    }
}

function northgate_template_minibio(){
    add_action('calpress_hook_post_below' , 'post_minibio');
    function post_minibio(){
        global $post;

        // primary author, for short bio
        $post_author = get_userdata(intval($post->post_author));

        // story lists multi authors?
        $bylines = get_post_custom_values('byline');

        // only if mini bio exist, and not using a byline extra field
        if (!empty($post_author->short_bio) && count($bylines) < 1) {
            $authorurl = get_author_posts_url( $post_author->ID, $post_author->user_nicename );
            echo '<div id="mini-bio">';
                echo '<h4>Author Bio</h4>';
                if ( userphoto_exists($post_author) ) { // upload bio pix exists
                    $photo_alt = "Profile photo: $post_author->display_name";
                    $profile_pic = calpress_croppedimage(WP_CONTENT_URL . '/uploads/userphoto/'.$post_author->userphoto_image_file, 50, 50, 1, $photo_alt);
                    echo "<a href=\"$authorurl\">$profile_pic</a>";
                }
                echo "<p>$post_author->short_bio <a class=\"fullbio\" href=\"$authorurl\">View full profile</a>.</p>";
            echo '</div>';
        }
    }
}

function northgate_template_articlesociallinks(){
    add_action('calpress_hook_postcontent_below' , 'articlesociallinks');
    function articlesociallinks(){
        global $post;
        $thisurl = urlencode(get_permalink($post->ID));
        $shorturl = BASEURL . '?p=' .$post->ID;// for use on twitter
        $title = get_the_title($post->ID);
        $thistitle = urlencode($title);
        echo '<ul class="sociallinks">
                <li><a class="facebook" href="http://www.facebook.com/sharer.php?u='. $thisurl . '&t='.$thistitle.'">Facebook</a></li>
                <li><a class="twitter" href="http://twitter.com/?status=' . $shorturl . ' '. $title . '">Twitter</a></li>
                <li><a class="delicious" href="http://www.delicious.com/save?url='. $thisurl . '">Delicious</a></li>
                <li><a class="stumbleupon" href="http://www.stumbleupon.com/submit?url='. $thisurl . '">StumbleUpon</a></li>
                <li><a class="digg" href="http://www.digg.com/submit?url='. $thisurl . '">Digg</a></li>
            </ul>';
    }
}

function northgate_template_relevantposts(){
    add_action('calpress_hook_post_below' , 'morearticles');
    function morearticles(){
        global $post;

        // get more posts
        $post_to_get = 9;

        $relevant_posts = calpress_get_weighted_story_list($post_to_get, true, array($post->ID));
        if ( count($relevant_posts) >= $post_to_get && count($relevant_posts) % 3 == 0 ) {
            echo '<div id="article-more-posts">';
                echo '<h4>More from ' . get_bloginfo('name') . ':</h4>';

                // show articles
                $pcount = 1;
            ?>
                <div class="navi"></div>


                <div class="naviarrows">
                    <a class="prev browse left"></a>
                    <a class="next browse right"></a>
                </div>

                <div class="scrollable" id="browsable">
                    <div class="items">
            
                <?php
                $tmpCounter = 0;
                foreach ($relevant_posts as $relevant_post) {

                    $postdate = date( 'F d, Y', strtotime($relevant_post->post_date) );
                    $post_author = get_userdata(intval($post->post_author));
                    $authorurl = get_author_posts_url( $post_author->ID, $post_author->user_nicename );
    
                    if ($tmpCounter === 0) {
                        echo '<div class="relevant-post-row">';
                    }
    
                    echo '<div class="relevant-post hentry post publish p'. $pcount . '">';
                        echo '<div class="entry-image"><a href="' . get_permalink( $relevant_post->ID ) . '">';
                            echo calpress_croppedimage($relevant_post->attachment_file, 200, 120, 1);
                        echo "</a></div>";

                        echo '<h4 class="entry-title"><a href="' . get_permalink( $relevant_post->ID ) . '">' .  $relevant_post->post_title . '</a></h4>';
                    echo '</div><!-- //relevant-post -->';
                    $pcount++;
    
                    if ($tmpCounter === 2) {
                        $tmpCounter = 0;
                        echo ('</div><!-- //relevant-post-row-->');
                    } else {
                        $tmpCounter++;
                    }
                }//end foreach
                ?>
                    </div><!-- //.items -->
               </div><!-- //.scrollable -->
            </div>
<?php
         }//endif ( count($relevant_posts >= $posts_to_get) ) {
    }//morearticles
}//northgate_template_relevantposts

// facebook functionality

// insert facebook connect like button at top of posts 
function northgate_template_facebook_like(){
    if (function_exists('sfc_version') && function_exists('get_sfc_like_button')) {
        add_action('calpress_hook_postcontent_above', 'facebook_like');
        function facebook_like(){
            $options = get_option('sfc_options');
        	$button = get_sfc_like_button();
        	echo '<div class="facebook facebooklike">' . $button . '</div>';
        }
    } 
}

// insert facebook share button at the bottom of posts
function northgate_template_facebook_share(){
    if (function_exists('sfc_version') && function_exists('get_sfc_share_button') ) {
        add_action('calpress_hook_postcontent_below', 'facebook_share');
        function facebook_share(){
            $options = get_option('sfc_options');
        	$button = get_sfc_share_button();
        	echo '<div class="facebook facebookshare">' . $button . '</div>';
        }
    } 
}

// Facebook header status
function northgate_template_headerfacebook(){
    add_action('calpress_hook_header_posttitle', 'headerfacebook');
    function headerfacebook() {
       northgate_include_file('includes/facebook-header.php');
    }
}

// En espanol link
function northgate_template_enespanol(){
    add_action('calpress_hook_postcontent_above', 'calpress_spanishlink');
}

// Show date
function northgate_template_headerdate(){
    add_action('calpress_hook_header_pretitle', 'headerdate');
    function headerdate() {
       $date = date('l, F j, Y');
       echo '<p class="date">'. $date .'</p>';
    }
}

// Show weather by location (Yahoo WEOID). optionally, point to full weather page
function northgate_template_headerweather($woeid, $link=false){
    global $weather_woeid; /* do i need to make this a global to access in headerweather()? */
    $weather_woeid = $woeid;
    global $showweatherlink;
    if ($link) {
       $showweatherlink = true;
    } else {
        $showweatherlink = false;
    }
    add_action('calpress_hook_header_pretitle', 'headerweather', 10);
    function headerweather() {
        global $weather_woeid; 
        global $showweatherlink;
        $weather = new CalPress_Weather($weather_woeid);
        if ($showweatherlink) {
            $weather->weather_formatted_html(true);
        } else {
            $weather->weather_formatted_html();
        }
        
    }
}

// Filter tweets for footer (removede $tweet argument)
add_filter('aktt_tweet_display', 'northgate_tweet_filter');
function northgate_tweet_filter($tweet){
    global $aktt;
    $username = $aktt->twitter_username;
    $profileurl = aktt_profile_url($aktt->twitter_username);
    //$tweeturl = aktt_status_url($aktt->twitter_username, $tweet->tw_id);
    
    //our box is only big enough for about 140 chars including the username, so once that happens, we need to truncate
    if ( ( strlen($tweet) + strlen($username) ) > 140) {
       
        // capture the click through url before we truncate it off and strip the anchor tag
        $pattern = '/http:\/\/twitter.com\/'.$username.'\/statuses\/[0-9]*/';
        if (preg_match ($pattern, $tweet, $matches) ) {
           $tweeturl = $matches[0];
        }
        
        $tweetlength = 140 - strlen($username);
        $tweet = strip_tags(substr($tweet, 0, $tweetlength)) .'... <a href="' . $tweeturl .'">More</a>'; //stip tags incase there's an unclosed anchor
    }
    
    $tweet = '<p><span class="twitterhandle">@<a href="' . $profileurl . '">'.$username.'</a>:</span> <span class="tweet">' . $tweet . '</span></p>';
    return $tweet;
}

//  If called, add copyright notice to feed content. 
//  http://wordpress.org/extend/plugins/simple-feed-copyright/
function northgate_rss_copyright(){
    $copyright_notice = '<p>&copy;' . date("Y") . ' <a href="' . get_bloginfo('url') . '">' . get_bloginfo('name') . '</a>. All Rights Reserved.</p>.';
    add_filter('the_content', 'add_notice');
    function add_notice( $content ) {
    	global $notice;    
         if( is_feed() ) {
            return $content.$copyright_notice;
        } else {
            return $content;
        }
    }
}

//Choose a random comment from the called-out (shout-out) section
function northgate_random_featured_comment(){
	if(!is_admin()){
	    // North Gates randome featured call-out comment
	    add_action('wp_head', 'ng_random_comments');
	    function ng_random_comments(){
	        echo '
<script type="text/javascript">
	var randomCommentPicker = Math.floor(Math.random()*10) + 1;
	$(document).ready(function() {
		$(\'#featured-comment-number\'+randomCommentPicker).css(\'display\', \'block\').css(\'visibility\',\'visible\');
	});
</script>
	        ';
	    }
	}
}
//Create a new widget for a featured image in the sidebar.
class SidebarFeaturedStoryImage extends WP_Widget {

	function SidebarFeaturedStoryImage() {
		// Instantiate the parent object
		parent::WP_Widget( false, 'Featured Sidebar Image' );
	}

	function widget( $args, $instance ) {
	  extract( $args, EXTR_SKIP );
    $img_src = empty($instance['img_src']) ? ' ' : $instance['img_src'];
    $img_link = empty($instance['img_link']) ? '#' : $instance['img_link'];
    if(!empty( $img_src )){
      echo $before_widget;
      echo '<a href="'.$img_link.'" target="_self">' . calpress_croppedimage($img_src, 300, 94, 1, "Featured Story Link") . '</a>';
      echo $after_widget;
    }
	}

	function update( $new_instance, $old_instance ) {
    $instance = wp_parse_args($old_instance, $new_instance);
  	$instance['img_src'] = strip_tags($new_instance['img_src']);
    $instance['img_link'] = strip_tags($new_instance['img_link']);
    return $instance;
	}

	function form( $instance ) {
		$instance = wp_parse_args( (array) $instance, array( 'img_src' => '', 'img_link' => '' ) );
    if(isset($instance['img_src'])) $img_src = strip_tags($instance['img_src']);
    if(isset($instance['img_link'])) $img_link = strip_tags($instance['img_link']);
    ?>
      <p>To create a sidebar image to feature a story or package, enter in the full source URL to the image (starting with http://)</p> 
      <p>Next, enter in the link that this image should direct you to. Images need to be cropped to <strong>300x94</strong> and uploaded via the <a href="/wp-admin/upload.php"><strong>Media</strong></a> link. No externally hosted images allowed.</p>
      <?php if($img_src): ?>
        <p><strong>Current Image:</strong><br />
        <img src="/wp-content/themes/calpress/library/extensions/timthumb.php?src=<?php echo $img_src; ?>&amp;w=224&amp;h=70&amp;z=1" width="224" height="70" /><br />
        (If blank, something is wrong)
        </p>
      <?php endif; ?>
    	<p><label for="<?php echo $this->get_field_id('img_src'); ?>">Image source: <input class="widefat" id="<?php echo $this->get_field_id('img_src'); ?>" name="<?php echo $this->get_field_name('img_src'); ?>" type="text" value="<?php echo attribute_escape($img_src); ?>" /></label></p>
    	<p><label for="<?php echo $this->get_field_id('img_link'); ?>">Link when clicked: <input class="widefat" id="<?php echo $this->get_field_id('img_link'); ?>" name="<?php echo $this->get_field_name('img_link'); ?>" type="text" value="<?php echo attribute_escape($img_link); ?>" /></label></p>
	  <?php
	}
}

//set a global variable for text widgets
$text_widget_occurance = 0;

//Create a new widget for text ads in the sidebar.
class TextAdsSidebar extends WP_Widget {

	function TextAdsSidebar() {
		// Instantiate the parent object
		parent::WP_Widget( 'text_ads', 'Text Ads', array( 'description' => 'Text advertisements that appear under specific categories' ) );
	}

	function widget( $args, $instance ) {
	  global $text_widget_occurance;
	  extract( $args, EXTR_SKIP );
    $ad_text = empty($instance['ad_text']) ? '' : $instance['ad_text'];
    $ad_link = empty($instance['ad_link']) ? '' : $instance['ad_link'];
    $ad_catg = empty($instance['ad_catg']) ? '' : $instance['ad_catg'];
    if(!empty($ad_text) && !empty($ad_link) && !empty($ad_catg)){
      if(is_category($ad_catg)){
        echo $before_widget;
        echo '<a href="'.$ad_link.'" target="_blank">' . wp_kses_post($ad_text) . '</a>'."\n";
        echo $after_widget;
        $text_widget_occurance++;
      }
    }
	}

	function update( $new_instance, $old_instance ) {
    $instance = wp_parse_args($old_instance, $new_instance);
    $instance['ad_text'] = strip_tags($new_instance['ad_text']);
    $instance['ad_link'] = strip_tags($new_instance['ad_link']);
    $instance['ad_catg'] = strip_tags($new_instance['ad_catg']);
    return $instance;
	}

	function form( $instance ) {
		$instance = wp_parse_args( (array) $instance, array( 'ad_text' => '', 'ad_link' => '', 'ad_catg' => '' ) );
    if(isset($instance['ad_text'])) $ad_text = strip_tags($instance['ad_text']);
    if(isset($instance['ad_link'])) $ad_link = strip_tags($instance['ad_link']);
    if(isset($instance['ad_catg'])) $ad_catg = strip_tags($instance['ad_catg']);
    ?>
      <p>To create a text-only advertisement, enter the text, the link, and choose which category it should appear under.</p> 
      <p>All three elements are required.</p>
    	<p><label for="<?php echo $this->get_field_id('ad_text'); ?>">Ad Text:</label> <input class="widefat" id="<?php echo $this->get_field_id('ad_text'); ?>" name="<?php echo $this->get_field_name('ad_text'); ?>" type="text" value="<?php echo esc_attr($ad_text); ?>" /></p>
    	<p><label for="<?php echo $this->get_field_id('ad_link'); ?>">Ad Link:</label> <input class="widefat" id="<?php echo $this->get_field_id('ad_link'); ?>" name="<?php echo $this->get_field_name('ad_link'); ?>" type="text" value="<?php echo esc_attr($ad_link); ?>" /></p>
    	<p><label for="<?php echo $this->get_field_id('ad_catg'); ?>">Ad Category:</label> 
    	  <select class="widefat" id="<?php echo $this->get_field_id('ad_catg'); ?>" name="<?php echo $this->get_field_name('ad_catg'); ?>">
    	    <option value="<?php echo esc_attr($ad_catg); ?>"><?php echo $ad_catg; ?></option>
<?php $categories = get_categories(array('type'=>'post', 'orderby'=>'slug', 'order'=>'ASC', 'hide_empty'=>true, 'hierarchical'=>false));
      foreach ($categories as $category) {
        	$option = '    	    <option value="'.$category->slug.'">';
      	  $option .= $category->slug; //cat_name;
      	  $option .= '</option>'."\n";
      	  echo $option;
        }
?>
    	  </select></p>
	  <?php
	}
}

//Create a new widget for text ads in the sidebar.
class GenericAdvertisement extends WP_Widget {

	function GenericAdvertisement() {
		// Instantiate the parent object
		parent::WP_Widget( 'generic_ad', 'Generic Advertisement', array( 'description' => 'Put HTML code for a generic advertisement' ) );
	}

	function widget( $args, $instance ) {
	  global $text_widget_occurance;
	  extract( $args, EXTR_SKIP );
    $ad_html = empty($instance['ad_html']) ? '' : $instance['ad_html'];
    $ad_es = empty($instance['ad_es']) ? '' : $instance['ad_es'];
    if(!empty($ad_html)){
      if($ad_es == 'spanish'){
        if(in_category('en-espanol')){
          echo $before_widget;
          echo '<h3 class="advertisement">Anuncio</h3>'."\n";
          echo $ad_html."\n";
          echo $after_widget;
        }
      } else {
        if(!in_category('en-espanol')){
          echo $before_widget;
          echo '<h3 class="advertisement">Advertisement</h3>'."\n";
          echo $ad_html."\n";
          echo $after_widget;
        }
      }
    }
  }

	function update( $new_instance, $old_instance ) {
    $instance = wp_parse_args($old_instance, $new_instance);
    $instance['ad_html'] = $new_instance['ad_html'];
    $instance['ad_es'] = $new_instance['ad_es'];
    return $instance;
	}

	function form( $instance ) {
		$instance = wp_parse_args( (array) $instance, array('ad_html' => '', 'ad_es' => ''));
    if(isset($instance['ad_html'])) $ad_html = $instance['ad_html'];
    if(isset($instance['ad_es'])) $ad_es = $instance['ad_es'];
    ?>
      <p>To create a generic advertisement, type or paste in HTML code below.</p> 
    	<p><label for="<?php echo $this->get_field_id('ad_html'); ?>">HTML code only:</label> <textarea class="widefat" rows="16" cols="20" id="<?php echo $this->get_field_id('ad_html'); ?>" name="<?php echo $this->get_field_name('ad_html'); ?>"><?php echo esc_attr($ad_html); ?></textarea></p>
    	<p><input type="checkbox" name="<?php echo $this->get_field_name('ad_es'); ?>" id="<?php echo $this->get_field_id('ad_es'); ?>" value="spanish" <?php if($ad_es == 'spanish') echo 'checked="checked"'; ?> />Spanish Ad?</p>
    <?php
	}
}

function addtional_sidebar_register_widgets() {
	register_widget( 'SidebarFeaturedStoryImage' );
	register_widget( 'TextAdsSidebar' );
	register_widget( 'GenericAdvertisement' );
}

add_action( 'widgets_init', 'addtional_sidebar_register_widgets' );


?>